﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using YAPACS.RisServer.Abstractions;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Report;

public class Revisit(IRepository<BusinessObjects.Exams.Report, Guid> reportRepository, IExamEventService examEventService) : WorkflowBase, IRevisit, ITransientDependency
{
    private readonly IRepository<BusinessObjects.Exams.Report, Guid> _reportRepository = reportRepository;
    private readonly IExamEventService _examEventService = examEventService;

    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        const string key = "Input";
        if (input.ContainsKey(key) && input.GetValueOrDefault(key) is Dictionary<string, object> data)
        {
            if (Guid.TryParse(data.GetValueOrDefault("reportId")?.ToString(), out Guid reportId))
            {
                var report = await _reportRepository.GetAsync(reportId);

                var schema = data.GetValueOrDefault("schema")?.ToString();
                if (!string.IsNullOrWhiteSpace(schema))
                {
                    report.RevisitRecordSchema = schema;
                }
                data.Remove("schema");
                report.RevisitRecord = data.GetValueOrDefault("revisitRecord")?.ToString();
                //回访备注
                report.RevisitRemark = report.RevisitRecordJson["revisitRemark"]?.ToString();
                //回访时间
                if (DateTime.TryParse(report.RevisitRecordJson["revisitTime"]?.ToString(), out DateTime revisitTime))
                {
                    if (report.RevisitTime != revisitTime.Date)
                    {
                        report.RevisitTime = revisitTime.Date;
                        await _examEventService.AddExamEventAsync(report.Exam, "患者回访", $"患者回访时间：{revisitTime:yyyy-MM-dd}");
                    }
                }
                //回访实际时间
                if (bool.TryParse(report.RevisitRecordJson["isCompleted"]?.ToString(), out bool isRevisit))
                {
                    if (report.ActualRevisitTime == null && isRevisit)
                    {
                        report.ActualRevisitTime = Clock.Now;
                        await _examEventService.AddExamEventAsync(report.Exam, "完成回访");
                    }
                }
                //处理逻辑
                return new WorkflowOutput
                {
                    Success = true,
                    Data = data
                };
            }
        }
        return new WorkflowOutput
        {
            Success = false,
            Error = "未找到Exam对象",
        };
    }
}
